'use client';

import Image from 'next/image';
import Link from 'next/link';
import { useMutation, useQuery } from '@tanstack/react-query';
import { checkOauthClient, queryOauthClientByClientId } from '@/services/api';
import type { ICheckOauthClient, IOauthClient } from '@/interfaces';
import useToast from '@/hooks/useToast';
import { URLPattern } from 'next/server';
import type { IOauthAuthPageContext } from '@/contexts/oauth-auth';
import { OauthAuthPageContext } from '@/contexts/oauth-auth';
import { useContext } from 'react';
import { AppContext } from '@/contexts/app';

export default function OauthAuthPage({
  source,
  translatedFields,
}: IOauthAuthPageContext) {
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;
  const env = metadata.env;
  const { show } = useToast();

  const checkOauthClientMutation = useMutation(checkOauthClient);

  const queryOauthClientByClientIdQuery = useQuery(
    ['/oauth', '/clients', source.queryParams.clientId, '/by'],
    async (context) => {
      return (await queryOauthClientByClientId({
        id: context.queryKey[2] + '',
      })) as IOauthClient;
    },
    {
      initialData: source.client,
    },
  );

  async function onClickAgreeAuthorize() {
    try {
      const queryParams = source.queryParams;
      const data = (await checkOauthClientMutation.mutateAsync({
        data: queryParams,
      })) as ICheckOauthClient;

      if (queryParams.state && queryParams.state !== data.state) {
        show({
          type: 'DANGER',
          message: translatedFields.unidentifiedAuthServer,
        });

        setTimeout(() => {
          show({
            type: 'DANGER',
            message: translatedFields.accessTerminated,
          });
        }, 2000);

        setTimeout(() => {
          location.href = '/';
        }, 3000);

        return;
      }

      show({
        type: 'SUCCESS',
        message: translatedFields.agreeAccessComplete,
      });

      setTimeout(() => {
        show({
          type: 'PRIMARY',
          message: translatedFields.redirecting,
        });
      }, 1000);

      setTimeout(() => {
        if (data.code && queryParams.redirectUri) {
          let href = `${queryParams.redirectUri}?code=${data.code}&state=${
            data.state || ''
          }`;

          if (queryParams.redirectUri.includes('/yw')) {
            href += `&clientId=${queryParams.clientId}`;
          }

          location.href = href;
        } else if (queryParams.redirectUri) {
          const urlPattern = new URLPattern(queryParams.redirectUri);
          location.href = `${urlPattern.protocol}://${urlPattern.hostname}`;
        } else {
          show({
            type: 'DANGER',
            message: translatedFields.failToRedirect,
          });

          setTimeout(() => {
            show({
              type: 'INFO',
              message: translatedFields.tryManuallyReturn,
            });
          }, 1500);
        }
      }, 1500);
    } catch (e) {
      checkOauthClientMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onClickCancelAuthorization() {
    show({
      type: 'SUCCESS',
      message: translatedFields.accessCancelled,
    });

    setTimeout(() => {
      show({
        type: 'INFO',
        message: translatedFields.toCancelAccessGoToMyPage,
      });
    }, 1000);

    setTimeout(() => {
      const urlPattern = new URLPattern(source.queryParams.redirectUri);
      location.href = `${urlPattern.protocol}://${urlPattern.hostname}`;
    }, 2000);
  }

  return (
    <OauthAuthPageContext.Provider value={{ source, translatedFields }}>
      <div className="container-fluid p-2 vh-100">
        <div className="text-center h3 py-5">
          {translatedFields.openAuthInProgress}
        </div>
        <div
          className="row py-5 justify-content-center gap-5 mx-1"
          style={{ background: 'var(--bs-body-bg)' }}
        >
          <div className="col-12 col-md-5 col-lg-3">
            <div className="vstack gap-4">
              <div className="hstack gap-4 align-items-center">
                <div>
                  <Link
                    href={queryOauthClientByClientIdQuery.data.website || '#'}
                  >
                    {queryOauthClientByClientIdQuery.data.logo ? (
                      <Image
                        className="object-fit-cover rounded-circle"
                        src={queryOauthClientByClientIdQuery.data.logo}
                        alt={queryOauthClientByClientIdQuery.data.name}
                        title={queryOauthClientByClientIdQuery.data.name}
                        width={48}
                        height={48}
                        placeholder="blur"
                        blurDataURL={env.APP_BLUR_DATA_URL}
                      />
                    ) : (
                      <div
                        title={`${queryOauthClientByClientIdQuery.data.name} ${translatedFields.noAppIconSet}`}
                        className="rounded-circle bg-light"
                        style={{ width: 48, height: 48 }}
                      />
                    )}
                  </Link>
                </div>
                <div
                  className="fw-medium"
                  title={
                    queryOauthClientByClientIdQuery.data.overview ||
                    queryOauthClientByClientIdQuery.data.name
                  }
                >
                  <Link
                    className="text-decoration-none text-decoration-underline-hover link-dark fw-medium"
                    href={queryOauthClientByClientIdQuery.data.website || '#'}
                  >
                    {queryOauthClientByClientIdQuery.data.name}
                  </Link>
                </div>
              </div>
              <div>
                <i className="bi bi-info-circle me-2"></i>
                {translatedFields.authorizingAppNameLogin}
              </div>
              <div className="text-secondary">
                <ul className="vstack gap-2">
                  <li className="hstack align-items-center gap-2">
                    <div>{translatedFields.linkYourAccount}</div>
                    <input
                      className="form-check-input mt-0"
                      type="checkbox"
                      value=""
                      checked
                      disabled
                    />
                  </li>
                  <li className="hstack align-items-center gap-2">
                    <div>{translatedFields.accessAliasSignAvatar}</div>
                    <input
                      className="form-check-input mt-0"
                      type="checkbox"
                      value=""
                      checked
                      disabled
                    />
                  </li>
                </ul>
              </div>
              <div className="text-secondary">
                {translatedFields.dataManagedByPrivacyPolicy}
                <Link
                  className="text-decoration-none text-decoration-underline-hover"
                  href={`/users/${source.path.user!.id}`}
                >
                  {translatedFields.myPage}
                </Link>
                {translatedFields.cancelAppAccess}
              </div>
            </div>
          </div>
          <div className="d-none d-md-block col-md-auto">
            <div className="vr h-100 text-secondary"></div>
          </div>
          <div className="col-12 col-md-5 col-lg-3 align-self-center">
            <div className="d-grid gap-4">
              <button
                disabled={
                  checkOauthClientMutation.isLoading ||
                  checkOauthClientMutation.isSuccess
                }
                onClick={onClickAgreeAuthorize}
                className="btn btn-primary"
                type="button"
              >
                {checkOauthClientMutation.isLoading ? (
                  <span
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                ) : (
                  <i className="bi bi-check-lg me-2"></i>
                )}
                {translatedFields.agreeAccess}
              </button>
              <button
                disabled={
                  checkOauthClientMutation.isLoading ||
                  checkOauthClientMutation.isSuccess
                }
                onClick={onClickCancelAuthorization}
                className="btn btn-light"
                type="button"
              >
                <i className="bi bi-x-lg me-2"></i>
                {translatedFields.cancelAccess}
              </button>
            </div>
          </div>
        </div>
        <div style={{ paddingBottom: '2rem', paddingTop: '2rem' }}></div>
      </div>
    </OauthAuthPageContext.Provider>
  );
}
